package com.weichai.app.page.login.viewmodel;

import static com.weichai.app.App.APP_ID;
import static com.weichai.app.page.common.PrivacyFragment.KEY_PRIVACY_TYPE;
import static com.weichai.app.page.login.view.BindPhoneFragment.*;

import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import androidx.databinding.DataBindingUtil;
import androidx.databinding.ObservableField;

import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.weichai.app.App;
import com.weichai.app.R;
import com.weichai.app.arch.base.BaseViewModel;
import com.weichai.app.arch.http.ApiManager;
import com.weichai.app.arch.http.ApiSubscriber;
import com.weichai.app.arch.http.ApiTransformer;
import com.weichai.app.arch.utils.UserInfoManager;
import com.weichai.app.bean.BaseResult;
import com.weichai.app.bean.UserInfo;
import com.weichai.app.page.common.dialog.AlertDialog;
import com.weichai.app.page.mine.UserCenterVM;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

import dev.utils.LogPrintUtils;
import dev.utils.common.validator.ValiToPhoneUtils;
import io.reactivex.rxjava3.core.Observable;

public class LoginVM extends BaseViewModel {
    public ObservableField<String> textPhone = new ObservableField<>();//手机号
    public ObservableField<String> textPsw = new ObservableField<>();//手机密码
    public ObservableField<Boolean> checkPrivacy = new ObservableField<>(true);//
    public ObservableField<Integer> phoneErrVisible = new ObservableField<>(View.GONE);//
    public ObservableField<Boolean> enableCommitBtn = new ObservableField<>(false);//是否可用提交按钮
    public ObservableField<Boolean> isShowPwd = new ObservableField<>(false);//密码是否可见

    //导航到忘记密码页面
    public void navForgetPwdPage() {
        navigate(R.id.forget_pwd_page);
    }

    //导航到注册页面
    public void navRegisterPage() {
        navigate(R.id.register_page);
    }

    ///验证码登录
    public void navVerifyCodePage() {
        navigate(R.id.verify_code_login);
    }

    //文字变化监听
    public void onTextChanged(CharSequence value, int i, int i1, int i2) {
        ///延迟获取最新输入值
        Observable.just(1)
                .delay(25, TimeUnit.MILLISECONDS)
                .subscribe(integer -> {
                    if (!TextUtils.isEmpty(textPhone.get()) && !ValiToPhoneUtils.isPhoneCheck(textPhone.get())) {
                        phoneErrVisible.set(View.VISIBLE);
                    } else {
                        phoneErrVisible.set(View.GONE);
                    }
                    enableCommitBtn.set(checkCommit());
                });
    }


    //检测密码是否正确
    private boolean checkPwd() {
        return (!TextUtils.isEmpty(textPsw.get()) && Pattern.matches("^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$", textPsw.get()));
    }

    ///登录
    public void loginCommit() {
        if (!checkPrivacy.get()) {
            showToast("请同意用户隐私协议");
            return;
        }

        if (!checkPwd()) {
            showToast("密码6-20位由数字和字母组成");
            return;
        }
        HashMap<String, String> appParams = new HashMap<>();
        appParams.put("userName", textPhone.get());
        appParams.put("password", textPsw.get());
        ApiManager.getInstance()
                .loginByPwd(appParams)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<UserInfo>(true, true, this) {
                    @Override
                    public void onSuccess(BaseResult<UserInfo> result) {
                        getViewModelOfApp(UserCenterVM.class).updateUserInfo(result.data);
//                        UserInfoManager.getInstance().setUserInfo(result.data);
                        showToast("登录成功");
                        navigate(R.id.login_to_main_page);
                    }
                });
    }

    /**
     * 检查是否可以点击登录
     *
     * @return 是/否
     */
    public boolean checkCommit() {

        if (!ValiToPhoneUtils.isPhoneCheck(textPhone.get())) {
            return false;
        }

        if (TextUtils.isEmpty(textPsw.get())) {
            return false;
        }

        return true;
    }

    /**
     * 微信登录
     */
    public void naxWxLoginPage() {
        SendAuth.Req req = new SendAuth.Req();
        req.scope = "snsapi_userinfo";
        req.state = "wechat_sdk_demo_test";
        WXAPIFactory.createWXAPI(App.getApp(), APP_ID, true).sendReq(req);
    }

    /**
     * 微信登录
     *
     * @param code 微信返回的code
     */
    public void loginWxByCode(String code) {
        ApiManager.getInstance()
                .wechatLogin(code)
                .compose(new ApiTransformer<>())
                .subscribeWith(new ApiSubscriber<UserInfo>(true, true, this) {
                    @Override
                    public void onSuccess(BaseResult<UserInfo> result) {
                        if (result.data.phoneBindingStatus == 0) {//未绑定情况
                            Bundle args = new Bundle();
                            args.putString(WX_OPENID, result.data.openId);
                            args.putString(WX_NICK, result.data.nickName);
                            args.putString(WX_UNION, result.data.unionId);
                            args.putString(WX_USER_CODE, result.data.userCode);
                            args.putString(WX_AVATAR, result.data.header);
                            navigate(R.id.bind_phone_page, args);
                        }
                        if (result.data.phoneBindingStatus == 1) {//未绑定情况
                            navigate(R.id.login_to_main_page);
                            getViewModelOfApp(UserCenterVM.class).updateUserInfo(result.data);
                            showToast("登录成功");
                        }
                    }
                });
    }

    public void showPwd() {
        isShowPwd.set(!isShowPwd.get());
    }

    public void navPrivacyPage(int type) {
        Bundle param = new Bundle();
        param.putString(KEY_PRIVACY_TYPE, String.valueOf(type));
        navigate(R.id.privacy_page, param);
    }

    /**
     * 账号登录
     */
    public void accountLogin(UserCenterVM centerVM) {
        textPhone.set("");
        centerVM.clearUserInfo();
    }
}